package cn.thoughtworks.school.controllers;

import cn.thoughtworks.school.annotations.Auth;
import cn.thoughtworks.school.entities.Notification;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.exceptions.BusinessException;
import cn.thoughtworks.school.repositories.NotificationRepository;
import cn.thoughtworks.school.services.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/notifications")
public class NotificationController {

  @Autowired
  private NotificationRepository notificationRepository;
  @Autowired
  private NotificationService notificationService;


  @GetMapping(value = "/users/{userId}")
  public ResponseEntity getNotifications(@PathVariable Long userId,
                                         @RequestParam String status,
                                         @PageableDefault(page = 1, sort = {"id"}, direction = Sort.Direction.DESC)
                                           Pageable pageable) {
    return ResponseEntity.ok(notificationService.getNotifications(userId, status, pageable));
  }


  @PutMapping(value = "/{notificationId}")
  public ResponseEntity changeStatus(@PathVariable Long notificationId,
                                     @RequestParam(value = "status", defaultValue = "unRead") String status) throws BusinessException {
    Notification notification = notificationRepository.findById(notificationId).orElseThrow(
      () -> new BusinessException("current notification is not exist")
    );
    notificationService.changeStatus(status, notification);

    return new ResponseEntity(HttpStatus.NO_CONTENT);
  }

  @PutMapping(value = "")
  public ResponseEntity markAll(@Auth User current, @RequestParam(value = "status") String status) {
    notificationService.markAll(current.getId(), status);

    return new ResponseEntity(HttpStatus.NO_CONTENT);
  }


  @PostMapping("")
  public ResponseEntity addNotification(@RequestBody Map data) {
    List<Notification> notifications = notificationService.addNotification(data);

    return new ResponseEntity(notifications, HttpStatus.CREATED);
  }

}
